﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Business.Service;
using Model;
using System.Net;
using System.Text;
using System.Configuration;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Reflection;
using System.Web.Security;
using Newtonsoft.Json;

namespace MvcAppWeb.Controllers
{
    public class DCJDOrderInfoController : BaseDataController
    {
        //
        // GET: /DCJDOrderInfo/

        public ActionResult DCJDOrderInfo()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);

            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="sBatchNO"></param>
        /// <param name="sGoodsCode"></param>
        /// <param name="sFlag"></param>
        /// <param name="checkTimeS"></param>
        /// <param name="checkTimeE"></param>
        /// <param name="cellNo"></param>
        /// <param name="sGoodsName"></param>
        /// <returns></returns>
        public JsonResult InitJsonResult(string OrderCode, string checkTimeS, string checkTimeE, string Status, string disGs, string disStatus)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            string where = " where 1=1 ";


            if (!string.IsNullOrEmpty(OrderCode))
            {
                where += " and OrderCode='" + OrderCode + "'";
            }
            if (!string.IsNullOrEmpty(checkTimeS))
            {
                where += " and JDORDERCREATETIME>= to_date('" + checkTimeS + "','yyyy-mm-dd')";
            }
            if (!string.IsNullOrEmpty(checkTimeE))
            {
                where += " and JDORDERCREATETIME<= to_date('" + checkTimeE + "','yyyy-mm-dd')+1";
            }
            if (Status != "")
            {
                where += " and status='" + Status + "'";
            }
            if (disGs != "")
            {
                where += " and DistributionType='" + disGs + "'";
            }
            if (disStatus != "")
            {
                where += " and DistributionStatus='" + disStatus + "'";
            }
            where += @" order by JDORDERCREATETIME,OrderCode ";


            BDCJDOrder bi = new BDCJDOrder();
            var result = bi.GetDCJDOrderList(page, rows, out total, where);

            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", result);
            return Json(json, JsonRequestBehavior.AllowGet);
        }




        [HttpPost]
        public JsonResult QueryDetailData(string ORDERCODE)
        {

            BDCJDOrder bi = new BDCJDOrder();
            var result = bi.GetGetDCJDOrderListDetailByORDERCODE(ORDERCODE);

            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("rows", result);
            return Json(json, JsonRequestBehavior.AllowGet);


        }

        [HttpPost]
        /// <summary>
        /// 分配订单配送方式
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string SaveDataDis()
        {
            string orderIDList = Request["hiddenOrderID"];
            string selectDis = Request["selectDis"];
            string sjson = string.Empty;


            if (orderIDList != null && orderIDList != "")
            {

                bool b = false;
                BDCJDOrder bi = new BDCJDOrder();
                if (orderIDList.IndexOf(',') > -1)
                {
                    orderIDList = orderIDList.Substring(0, orderIDList.Length - 1);
                    foreach (var orderid in orderIDList.Split(','))
                    {
                        DCJDOrder db = new DCJDOrder();
                        db.ORDERID = Convert.ToInt32(orderid);
                        db.DISTRIBUTIONTYPE = selectDis;
                        if (selectDis == "2")
                        {
                            List<DCJDOrder> list = bi.GetDCJDOrderListByOrderid(orderid);
                            if (list.Count > 0)
                            {
                                sjson = PostOrder(list[0]);
                                JObject responseJObject = JObject.Parse(sjson);
                                //API调用结果
                                string status = responseJObject["status"].ToString();

                                if (status == "ok")
                                {
                                    string ddorderId = responseJObject["orderid"].ToString();
                                    decimal fee = Convert.ToDecimal(responseJObject["fee"].ToString());
                                    db.THIRDDISORDER = ddorderId;
                                    db.THIRDDISPRICE = fee;
                                    int nnumber = bi.UpdateDCJDorderDISstatus(db);
                                    if (nnumber > 0)
                                    {
                                        sjson = "{success:true,msg:'推送成功！'}";
                                    }
                                    else
                                    {
                                        sjson = "{success:false,msg:'修改失败！'}";
                                    }
                                }

                            }

                        }
                        int n = bi.UpdateDCJDorderDISType(db);
                    }

                }

                if (b)
                {
                    sjson = "{success:true,msg:'修改成功'}";
                }
                else
                {
                    sjson = "{success:true,msg:'修改失败'}";
                }
            }
            else
            {
                sjson = "{success:false,msg:'请选择数据后再批量修改'}";
            }

            return sjson;
        }


        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        public string GetDDToKen()
        {
            string daDaUrl = ConfigurationManager.AppSettings["DaDaUrl"];
            string appKey = ConfigurationManager.AppSettings["DaDaAppKey"];
            string sjson = "";
            string grant_codeUrl = daDaUrl + "/oauth/authorize/?app_key=" + appKey + "&scope=dada_base";
            string grant_code = GetDaDa(grant_codeUrl);
            if (grant_code.Contains("ok"))
            {
                JObject responseJObject = JObject.Parse(grant_code);
                //API调用结果
                JToken jtoken = responseJObject["result"];
                grant_code = jtoken["grant_code"].ToString();
            }
            else
            {
                sjson = "{success:false,msg:'获取token失败请与IT部门联系！'}";
            }
            string tokenUrl = daDaUrl + "/oauth/access_token/?grant_type=authorization_code&app_key=" + appKey + "&grant_code=" + grant_code + "";
            string token = GetDaDa(tokenUrl);
            if (token.Contains("ok"))
            {
                JObject responseJObject = JObject.Parse(token);
                //API调用结果
                JToken jtoken = responseJObject["result"];
                sjson = jtoken["access_token"].ToString();
            }
            else
            {
                sjson = "{success:false,msg:'获取token失败请与IT部门联系！'}";
            }
            return sjson;
        }

        /// <summary>
        ///Get方式获取接口数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetDaDa(string url)
        {
            try
            {
                WebClient wc = new WebClient();
                wc.Headers.Add("Accept", "text/plain");
                wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
                Stream st = wc.OpenRead(url);
                StreamReader sr = new StreamReader(st);
                string res = sr.ReadToEnd();
                sr.Close();
                st.Close();

                return res;
            }
            catch
            {
                return string.Empty;
            }
        }


        /// <summary>  
        /// DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time"> DateTime时间格式</param>  
        /// <returns>Unix时间戳格式</returns>  
        public int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 提交接口
        /// </summary>
        public string PostOrder(DCJDOrder order)
        {
            try
            {
                string token = GetDDToKen();
                int timestamp = ConvertDateTimeInt(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

                Dictionary<string, string> dc = new Dictionary<string, string>();
                dc.Add("token", token);
                dc.Add("timestamp", timestamp.ToString());
                dc.Add("dada", "dada");
                string md5 = GetMD5String(dc);

                if (token.IndexOf("失败") > -1)
                {
                    return token;
                }
                else
                {
                    string url = ConfigurationManager.AppSettings["DaDaAddOrderUrl"];

                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine(string.Format("token={0}&timestamp={1}&signature={2}&" +
                    "origin_id={3}&city_name={4}&city_code={5}&pay_for_supplier_fee={6}&fetch_from_receiver_fee={7}&deliver_fee={8}&tips={9}&" +
                    "create_time={10}&info={11}&cargo_type={12}&cargo_weight={13}&cargo_price={14}&cargo_num={15}&" +
                    "is_prepay={16}&expected_fetch_time={17}&expected_finish_time={18}&supplier_id={19}&supplier_name={20}&supplier_address={21}&supplier_phone={22}&" +
                    "supplier_tel={23}&supplier_lat={24}&supplier_lng={25}&invoice_title={26}&receiver_name={27}&receiver_address={28}&receiver_phone={29}&" +
                    "receiver_tel={30}&receiver_lat={31}&receiver_lng={32}&callback={33}", token, timestamp,
                    md5, order.ORDERID, "上海", "021", 0, 0, 0, 0, 1467884625, "测试", 1, 1, order.SUMPRICE, order.GOODSNUMBER, 0, 5, 7200, "0",
                    "我厨", "长宁云雾山路569号", "15021751587", "", "121.514858", "121.514858", "发票抬头", order.RECEIVER, order.RECEIVERADDRESS, order.RECEIVERPHONE, "", order.RECEIVERLAT,
                    order.RECEIVERLNG, ""));
                    return Post(url, sb.ToString());
                }
            }
            catch (Exception ex)
            {
                return "{success:false,msg:'调用接口异常！'}";
            }

        }


        public string Post(string url, string paramData)
        {
            try
            {
                // 创建一个新的 WebClient 实例.
                WebClient myWebClient = new WebClient();
                // 注意这种拼字符串的ContentType
                myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                // 转化成二进制数组
                byte[] byteArray = Encoding.ASCII.GetBytes(paramData);
                // 上传数据，并获取返回的二进制数据.
                byte[] responseArray = myWebClient.UploadData(url, "POST", byteArray);
                string str = System.Text.Encoding.Default.GetString(responseArray);
                return str;
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

        /// <summary>
        /// 签名算法
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="app_secret"></param>
        /// <returns></returns>
        public string GetMD5String(Dictionary<string, string> dic)
        {
            Object[] values_arr = dic.Values.ToArray();
            Array.Sort(values_arr);
            StringBuilder sysStr = new StringBuilder();
            foreach (Object val in values_arr)
            {
                ;
                sysStr.Append(val);
            }
            return FormsAuthentication.HashPasswordForStoringInConfigFile(sysStr.ToString(), "MD5").ToLower();
        }
        [HttpPost]
        public string ExporterExcelDetail(string OrderCode, string checkTimeS, string checkTimeE, string Status, string disGs, string disStatus, string Ispreview = "0")
        {
            string sjson = string.Empty;
            BDCJDOrder db = new BDCJDOrder();
            DateTime RationDate;
            if (DateTime.TryParse(checkTimeS, out RationDate))
            {
                checkTimeS = RationDate.ToString("yyyy-MM-dd");
            }
            List<DCJDOrder> lstDCJDOrder = db.GetDCJDOrderListForPrint(OrderCode, checkTimeS, checkTimeE, Status, disGs, disStatus).ToList();//获取分拣单信息
            List<DCJDOrderDetail> listDetail = db.GetGetDCJDOrderListDetailForPrint(OrderCode, checkTimeS, checkTimeE, Status, disGs, disStatus).ToList();//获取分拣单信息

            if (lstDCJDOrder.Count <= 0)
                return "{success:false,msg:'没有符合条件的订单'}";
            foreach (DCJDOrder item in lstDCJDOrder)
            {
                item.DCJDOrderDetails = listDetail.Where(_ => _.ORDERID == item.ORDERID).ToList();
                //item.TOTALQTY = listDetail.Where(_ => _.SHEETID == item.SHEETID).Sum(_ => _.QTY);
            }
            //List<OrderInfo_Print_His> lstOrderInfo_Print_His = GetOrderInfo_Print_His(lstPrintOrderInfo);
            if (Ispreview == "1")//预览不打印
            {
                string strPrintOrderInfo = JsonConvert.SerializeObject(lstDCJDOrder[0]);
                sjson = "{success:true,msg:'',info:" + strPrintOrderInfo + "}";
                return sjson;
            }
            string strPrintJDOrderInfo = JsonConvert.SerializeObject(lstDCJDOrder);
            sjson = "{success:true,msg:'',info:" + strPrintJDOrderInfo + "}";
            //}
            //else
            //    sjson = "{success:false,msg:'执行失败'}";

            return sjson;
        }

        [HttpPost]
        public string ExporterWOC(string txtPrintInfo)
        {
            string sjson = "{success:true,msg:'',info:''}";
            string strGoods = string.Empty;
            List<Goods> lstGoods = new List<Goods>();
            if (txtPrintInfo.StartsWith("WOC"))
            {
                lstGoods = new BGoodsCellNo().GetGoodsDetail(txtPrintInfo);
                if (lstGoods.Count > 0)
                {
                    strGoods = JsonConvert.SerializeObject(lstGoods);
                    sjson = "{success:true,msg:'',info:" + strGoods + "}";
                }
            }

            return sjson;
        }

    }
}
